home *** CD-ROM | disk | FTP | other *** search
- /* randarg -- select random argument */
- /* copyright 1987 Michael M Rubenstein */
-
- #include <stdio.h>
-
- #define LINESIZE 128
-
- static int from_file = FALSE;
- static int do_command = FALSE;
-
- extern char *fgets();
- extern int optind;
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- char line[LINESIZE + 1];
- int i, n;
- FILE *infile;
-
- while ((n = getopt(argc, argv, "cfh")) != EOF)
- switch (n)
- {
- case 'f': from_file = TRUE;
- break;
-
- case 'c': do_command = TRUE;
- break;
-
- case 'h':
- default: help();
- exit(1);
- }
-
- argc -= optind;
- argv += optind;
-
- if (argc > 0)
- if (from_file)
- {
- if ((infile = fopen(argv[0], "r")) == NULL)
- {
- fprintf(stderr, "randarg: Cannot open %s\n", argv[0]);
- exit(1);
- }
- if (fgets(line, LINESIZE, infile) == NULL)
- return;
- n = atoi(line);
- if (n > 0)
- {
- for (i = irand(n); i >= 0; --i)
- if (fgets(line, LINESIZE, infile) == NULL)
- break;
- if (i < 0)
- output(line);
- }
- fclose(infile);
- }
- else
- output(argv[irand(argc)]);
- }
-
- /* output line to stdout or do command, depending on do_command */
- output(line)
- char line[];
- {
- int i;
-
- if ((i = strlen(line)) > 0 && line[i - 1] == '\n')
- line[i - 1] = '\0';
- if (line[0] != '\0')
- if (do_command)
- system(line);
- else
- printf("%s\n", line);
- }
-
- /* generate random number */
- irand(max)
- int max;
- {
- unsigned rslt;
- long tloc;
-
- time(&tloc);
- rslt = (tloc ^ (tloc >> 16)) | 1;
- rslt *= 13;
- return (rslt / 8) % max;
- }
-
- /* show how to use */
- help()
- {
- static char *msg[] =
- {
- "syntax: randarg [-c] <args>...\n",
- " or: randarg [-c] -f <infile>\n\n",
- "The first form randomly selects an argument and writes it to stdout\n",
- "(if not -c) or executes it (if -c).\n\n",
- "The second form randomly selects a line from <infile> and writes it\n",
- "to stdout or executes it. The first line of <infile> must contain\n",
- "the number of lines in the remainder of the file\n",
- NULL
- };
- char **p;
-
- for (p = msg; *p != NULL; ++p)
- fputs(*p, stderr);
- }
-